﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TianYuan.Data.Dapper
{
    public class DbContextBase : SqlSugarClient
    {
        /// <summary>
        /// 初始化数据库信息
        /// </summary>
        /// <param name="connname">数据库连接名称</param>
        /// <param name="dbType">数据库类型</param>
        /// <param name="cacheService">缓存服务</param>
        public DbContextBase(string connname, SqlSugar.DbType dbType, ICacheService cacheService) : base(new ConnectionConfig()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[connname].ConnectionString,
            DbType = dbType,//SqlSugar.DbType.MySql,
            ConfigureExternalServices = new ConfigureExternalServices()
            {
                DataInfoCacheService = cacheService, //Setting external cache service
            },
            IsAutoCloseConnection = false
        })
        {
            this.Connection = Ado.Connection;
            
#if DEBUG
            Debug.WriteLine("ContextID：" + ContextID);
#endif

        }

        public bool HasActiveTransaction
        {
            get
            {
                
                return Ado.Transaction != null;
            }
        }
        /// <summary>
        /// IDbConnection对象,支持Dapper、SqlHelper查询查询
        /// </summary>
        public IDbConnection Connection { get; private set; }

        public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            Ado.BeginTran();
            
        }
        public void Commit()
        {
            Ado.CommitTran();
        }

        public void Rollback()
        {
            Ado.RollbackTran();
        }
    }
}
